//----------------------------------------------
//            NGUI: Next-Gen UI kit
// Copyright © 2011-2015 Tasharen Entertainment
//----------------------------------------------

using System.CodeDom;
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Text;

[CanEditMultipleObjects]
[CustomEditor(typeof(UILocalize), true)]
public class UILocalizeEditor : Editor
{
    List<string> mKeys;

    void OnEnable()
    {
        Dictionary<string, string[]> dict = Localization.dictionary;

        if (dict.Count > 0)
        {
            mKeys = new List<string>();

            foreach (KeyValuePair<string, string[]> pair in dict)
            {
                if (pair.Key == "KEY") continue;
                mKeys.Add(pair.Key);
            }
            mKeys.Sort(delegate(string left, string right) { return left.CompareTo(right); });
        }
    }
    GUIContent refresh = new GUIContent("Refresh", "Reload the localize file");
    bool show_more = false;
    public override void OnInspectorGUI()
    {
        serializedObject.Update();

        GUILayout.Space(6f);
        NGUIEditorTools.SetLabelWidth(80f);

        GUILayout.BeginHorizontal();
        // Key not found in the localization file -- draw it as a text field
        SerializedProperty sp = NGUIEditorTools.DrawProperty("Key", serializedObject, "key");
        if (GUILayout.Button(refresh))
        {
            show_more = false;
            Localization.localizationHasBeenSet = false;
        }
        string myKey = sp.stringValue;
        bool isPresent = (mKeys != null) && mKeys.Contains(myKey);
        GUI.color = isPresent ? Color.green : Color.red;
        GUILayout.BeginVertical(GUILayout.Width(22f));
        GUILayout.Space(2f);
        GUILayout.Label(isPresent ? "\u2714" : "\u2718", "TL SelectionButtonNew", GUILayout.Height(20f));
        GUILayout.EndVertical();
        GUI.color = Color.white;
        GUILayout.EndHorizontal();

        if (isPresent)
        {
            if (NGUIEditorTools.DrawHeader("Preview"))
            {
                NGUIEditorTools.BeginContents();

                string[] keys = Localization.knownLanguages;
                string[] values;

                if (Localization.dictionary.TryGetValue(myKey, out values))
                {
                    if (keys.Length != values.Length)
                    {
                        EditorGUILayout.HelpBox("Number of keys doesn't match the number of values! Did you modify the dictionaries by hand at some point?", MessageType.Error);
                    }
                    else
                    {
                        for (int i = 0; i < keys.Length; ++i)
                        {
                            GUILayout.BeginHorizontal();
                            GUILayout.Label(keys[i], GUILayout.Width(65f));

                            if (GUILayout.Button(values[i], "AS TextArea", GUILayout.MinWidth(80f), GUILayout.MaxWidth(Screen.width - 110f)))
                            {
                                (target as UILocalize).value = values[i];
                                GUIUtility.hotControl = 0;
                                GUIUtility.keyboardControl = 0;
                            }
                            GUILayout.EndHorizontal();
                        }
                    }
                }
                else GUILayout.Label("No preview available");

                NGUIEditorTools.EndContents();
            }
        }
        else if (mKeys != null && !string.IsNullOrEmpty(myKey))
        {
            GUILayout.BeginHorizontal();
            GUILayout.Space(80f);
            GUILayout.BeginVertical();
            GUI.backgroundColor = new Color(1f, 1f, 1f, 0.35f);

            int matches = 0;
            using (Dictionary<string, string[]>.Enumerator e = Localization.dictionary.GetEnumerator())
            {
                while (e.MoveNext())
                {
                    var key_value = e.Current;
                    bool fit = false;
                    StringBuilder tip = new StringBuilder();
                    tip.AppendLine(key_value.Key);
                    if (key_value.Key.StartsWith(myKey, System.StringComparison.OrdinalIgnoreCase) || key_value.Key.Contains(myKey))
                        fit = true;
                    for (int i = 0; i < key_value.Value.Length; i++)
                    {
                        tip.AppendLine(key_value.Value[i]);
                        if (key_value.Value[i].StartsWith(myKey, System.StringComparison.OrdinalIgnoreCase) || key_value.Value[i].Contains(myKey))
                            fit = true;
                    }
                    if (fit)
                    {
                        if (GUILayout.Button(new GUIContent(key_value.Key + " \u25B2", tip.ToString()), "CN CountBadge"))
                        {
                            sp.stringValue = key_value.Key;
                            GUIUtility.hotControl = 0;
                            GUIUtility.keyboardControl = 0;
                        }
                        if (++matches == 20 && !show_more)
                        {
                            if (GUILayout.Button("...and more", "CN StatusInfo"))
                            {
                                show_more = !show_more;
                            }
                            break;
                        }
                    }
                }
            }
            GUI.backgroundColor = Color.white;
            GUILayout.EndVertical();
            GUILayout.Space(22f);
            GUILayout.EndHorizontal();
        }

        serializedObject.ApplyModifiedProperties();
    }
}



#if UNITY_EDITOR
[InitializeOnLoad]
public class LocalizationLoader
{
    public const string LANGUAGE_FILE_NAME = "language";
    static LocalizationLoader()
    {
        Localization.loadFunction = LoadLanguage;
    }
    public static byte[] LoadLanguage(string path)
    {
        string[] paths = AssetDatabase.FindAssets("language");
        TextAsset textAsset = null;
        for (int i = 0; i < paths.Length; i++)
        {
            string assetPath = AssetDatabase.GUIDToAssetPath(paths[i]);
            if (assetPath.EndsWith("csv"))
            {
                textAsset = AssetDatabase.LoadAssetAtPath(assetPath, typeof (TextAsset)) as TextAsset;
                break;
            }
        }
        if(null==textAsset)
            throw new UnityEngine.MissingReferenceException("找不到语言配置表");
        return textAsset.bytes;
    }
}
#endif
